<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="70%"
    :before-close="handleClose"
    destroy-on-close
    draggable
    v-loading="loading"
  >
    <div class="table-wrapper">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="400"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="#" width="60" align="center" />
        <el-table-column prop="billNo" label="票号" min-width="160" show-overflow-tooltip />
        <el-table-column prop="acceptorName" label="承兑人" min-width="220" show-overflow-tooltip />
        <el-table-column prop="billAmount" label="票面金额（万）" width="140" align="center" />
        <el-table-column prop="create_time" label="创建时间" width="170" align="center" />
      </el-table>
    </div>
    <template #footer>
      <span>
        <el-button type="primary" @click="handleConfirm" :disabled="selectedRows.length === 0">
          确认 ({{ selectedRows.length }})
        </el-button>
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
/**
 * 详情弹框：负责加载并展示回撤记录的详情列表
 * 使用方法：父组件通过 ref 调用 open(row)
 */
import { ref } from "vue"
import { ElMessage } from "element-plus"
import { getOperationRecordDetailsApi } from "@/api/common/index"
import { deleteBillApi } from "@/api/billv2/index"

interface ListItem {
  id: number
  title: string
  content: string
  status: number
  create_time: string
  [key: string]: any
}

const visible = ref(false)
const loading = ref(false)
const dialogTitle = ref("详情")
const tableData = ref<any[]>([])
const currentRow = ref<ListItem | null>(null)
const selectedRows = ref<any[]>([])
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const emit = defineEmits(["confirm"])

const handleConfirm = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要确认的记录")
    return
  }
  // 从选中行提取 bill_id，过滤无效值并去重
  const billIds = Array.from(
    new Set(selectedRows.value.map((it: any) => it.bill_id).filter((id: any) => id !== undefined && id !== null))
  )

  if (billIds.length === 0) {
    ElMessage.warning("选中记录中未找到有效的票据ID")
    return
  }

  try {
    loading.value = true
    const billIdsJson = JSON.stringify(billIds)
    await deleteBillApi({ billIds: billIdsJson })
    ElMessage.success("操作成功")
    emit("confirm", selectedRows.value)
    handleClose()
  } catch (e) {
    ElMessage.error("操作失败，请稍后重试")
  } finally {
    loading.value = false
  }
}

const fetchDetails = async (row: ListItem) => {
  if (!row?.id) return
  loading.value = true
  try {
    const resp: any = await getOperationRecordDetailsApi({ id: row.id })
    const data = resp?.data
    tableData.value = Array.isArray(data?.data) ? data.data : []
  } catch (e) {
    ElMessage.error("加载详情失败，请稍后重试")
    tableData.value = []
  } finally {
    loading.value = false
  }
}

const open = (row: ListItem) => {
  currentRow.value = row
  dialogTitle.value = row?.title ? `详情 - ${row.title}` : "详情"
  visible.value = true
  fetchDetails(row)
}

const handleClose = () => {
  visible.value = false
  tableData.value = []
  currentRow.value = null
  dialogTitle.value = "详情"
}

defineExpose({
  open
})
</script>

<style scoped lang="scss">
.table-wrapper {
  margin-bottom: 16px;
}
</style>
